package com.zoe.vhr.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zoe.vhr.exception.VerifyCodeException;
import com.zoe.vhr.util.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/26
 * @Description 登录失败处理器
 */
@Configuration
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest req,
                                        HttpServletResponse resp,
                                        AuthenticationException e) throws IOException, ServletException {
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = resp.getWriter();
        R<String> failed;
        if (e instanceof BadCredentialsException) {
            failed = R.failed("账户或密码错误!请确认后重新输入");
        } else if (e instanceof CredentialsExpiredException) {
            failed = R.failed("密码过期!请联系管理员");
        } else if (e instanceof DisabledException) {
            failed = R.failed("账户被禁用!请联系网站管理员");
        } else if (e instanceof AuthenticationServiceException) {
            failed = R.failed("不支持的登录请求");
        } else if (e instanceof VerifyCodeException) {
            failed = R.failed("验证码不正确或已过期！");
        } else if (e instanceof SessionAuthenticationException) {
            failed = R.failed("您的账号已经登录,无法重新登录");
        } else {
            failed = R.failed("登录异常，请联系管理员！");
        }
        String s = new ObjectMapper().writeValueAsString(failed);
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
